<?php

namespace App\Admin\Service\Traits;


use App\Common\Exception\ApiMessageException;
use App\Common\Util\AdminAuth;
use App\Common\Util\ImitateAop\Attributes\Transaction;

/**
 * 软删除恢复操作
 *
 * @method beforeRecover(array $ids)
 * @method afterRecover(array $ids)
 */
trait RecoverServiceTrait
{

    /**
     * @param array $ids
     *
     * @return void
     * @throws ApiMessageException
     */
    #[Transaction]
    public function recover(array $ids): void
    {
        method_exists($this, 'beforeRecover') and $this->beforeRecover($ids);

        if (!AdminAuth::isSuper()) {
            throw new ApiMessageException("权限不足！");
        }

        if (empty($ids)) {
            throw new ApiMessageException("请选择要恢复的数据！");
        }

        $result = $this->model->onlyTrashed()->whereIn('id', $ids)->update([
            $this->model->getDeleteTimeField() => null,
            $this->model->getUpdateTimeField() => date('Y-m-d H:i:s')
        ]);

        if ($result) {
            method_exists($this, 'afterRecover') and $this->afterRecover($ids);
        }else {
            throw new ApiMessageException("恢复失败！");
        }
    }
}
